package lucky.xiong.煞笔面试题.JUC.threadLocal;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * threadLocal 和线程池一起时的规范。
 * <p>
 * 线程池会复用，此场景下，需要清理自定义的ThreadLocal变量，参照alibaba开发规范
 *
 * @author XiongJianLin
 * @date Created in 2024/12/3 15:50
 */

class BankEmployer {  //资源类
    ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);

    public void add() {
        threadLocal.set(threadLocal.get() + 1);
    }
}

public class TheadLocalAndThreadPool {
    public static void main(String[] args) {
        BankEmployer bankEmployer = new BankEmployer();
        // 模拟有三个窗口提供业务
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        try {
            // 提供10个请求，用线程池处理
            for (int i = 0; i < 10; i++) {
                int innerI = i;
                threadPool.submit(() -> {
                    try {
                        Integer before = bankEmployer.threadLocal.get();
                        bankEmployer.add();
                        Integer after = bankEmployer.threadLocal.get();
                        System.out.println(Thread.currentThread().getName() + "接收第 " + innerI + "请求，" + "before:" + before + " after:" + after);
                    } finally {
                        // 如果不清理就会发生内存泄露
                        bankEmployer.threadLocal.remove();
                    }
                });
            }

        } catch (Exception e) {


        } finally {
            threadPool.shutdown();
        }
    }

}
